<template>
  <div class="left-sub" ref="leftSubEle" v-if="isLoad">
    <el-tree class="el-tree" ref="leftTree" :data="treeData" node-key="id" :highlight-current="true"
      :default-expanded-keys="expandedList" @node-expand="(data) => { handleNode(data, 'expand') }"
      @node-collapse="(data) => { handleNode(data, 'collapse') }" @node-click="(data) => { handleNode(data, 'click') }"
      @check-change="(data) => { handleNode(data, 'change') }">
      <div class="tree-slot" slot-scope="{node, data}" @mouseover="(e) => { hoverTreeNode(e, data) }"
        @mouseout="(e) => { hoverTreeNode(e, data) }">
        <!-- 一级目录 -->
        <div class="level-1" v-if="data.level == 1">
          <div class="left-box">
            <img :src="require(`@/assets/image/leftSub/${data.icon}`)" alt="">
            <span>{{ data.label }}</span>
          </div>
        </div>

        <!-- 二级目录 -->
        <div class="level-2" v-if="data.level == 2 && data.children">
          <div class="left-box">
            <img :src="require(`@/assets/image/leftSub/${data.icon}`)" alt="">
            <span class="label beyond-txt" :title="data.label">{{ data.label }}</span>
          </div>

          <!-- 二级目录操作 -->
          <div class="right-box" @mouseover="(e) => { hoverNodeControl(e, data) }"
            @mouseout="(e) => { hoverNodeControl(e, data) }">
            <div class="img-box" v-for="(item, index) in data.control" :key="index"
              @click.stop="clickNodeControl(item, data)">
              <img :src="require(`@/assets/image/leftSub/${item.icon}`)" alt="" :data-index="index">
            </div>
          </div>

          <!-- 二级目录添加框 -->
          <div class="popup-box" :ref="`addPopup${data.id}`">
            <div class="item" v-for="(item, index) in addPopupList" :key="index"
              @click.stop="clickAddPopupItem(data, item)">
              <span>{{ item }}</span>
            </div>
          </div>
        </div>

        <!-- 三级目录 -->
        <div class="level-3" v-if="!data.children">
          <div class="left-box">
            <div :style="`width: ${data.attribute.isExist ? 100 : 79} px`" class="box-label"
              v-if="!data.attribute.isEdit">
              <span class="beyond-txt" :title="data.label"> {{ data.label }}</span>
              <img v-if="!data.attribute.isExist" src="@/assets/image/leftSub/感叹号.png" alt="">
            </div>
            <el-input ref="renameInput" v-model="data.label" v-else @blur="renameNode(data)"></el-input>
          </div>

          <div class="right-box" :class="{ 'not-exist': !data.attribute.isExist }"
            @mouseover="(e) => { hoverNodeControl(e, data) }" @mouseout="(e) => { hoverNodeControl(e, data) }">
            <div class="img-box" v-for="(item, index) in data.control" :key="index"
              @click.stop="clickNodeControl(item, data)">
              <img :src="require(`@/assets/image/leftSub/${item.icon}`)" alt="" :data-index="index">
            </div>
          </div>

          <!-- 三级目录拓展框 -->
          <div style="display: none;" class="popup-box" :ref="`morePopup${data.id}`">
            <div class="item" v-for="(item, index) in morePopupList" :key="index"
              @click.stop="clickMorePopupItem(item, data)">
              <span>{{ item }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-tree>

    <load-model-dialog ref="modelDialogEle" v-show="showModelDialog" :popupItemType="popupItemType"
      @appendModelNode="appendModelNode" @close="closeModelDialog"></load-model-dialog>
    <load-layer-dialog ref="layerDialogEle" v-show="showLayerDialog" :selectNode="selectNode"
      @appendLayerNode="appendLayerNode" @close="closeLayerDialog"></load-layer-dialog>
    <component :is="componentId" :selectLayerNode="selectLayerNode" @setLayerStyle="setLayerStyle"
       @close="closeLayerNodeLevel3"></component>
    <mark-info v-show="showMarkComponent" ref="markInfoEle" @appendMarkNode="appendMarkNode"
      @close="closeMarkPanel"></mark-info>
  </div>
</template>

<script>
import loadLayerDialog from '@/components/vectorLayer/loadLayerDialog.vue';
import layerStyle from '@/components/vectorLayer/layerStyle.vue';
import loadModelDialog from '@/components/3DModel/loadModelDialog.vue';
import markInfo from '@/components/markInfo/index.vue';
export default {
  components: { loadLayerDialog, loadModelDialog, layerStyle, markInfo },

  data () {
    return {
      isLoad: false,
      treeData: [
        {
          id: '1',
          level: 1,
          label: '三维场景',
          children: [
            {
              id: '1-1',
              level: 2,
              label: '三维模型',
              children: []
            },
            {
              id: '1-2',
              level: 2,
              label: '矢量数据',
              children: []
            },
            {
              id: '1-3',
              level: 2,
              label: '影像数据',
              children: [
              ]
            },
            {
              id: '1-5',
              level: 2,
              label: '标注信息',
              children: []
            }
          ]
        }
      ],
      expandedList: ['1', '1-1', '1-2', '1-3', '1-5'],
      addPopupList: [],
      popupItemType: '',
      showModelDialog: false,
      showLayerDialog: false,
      showMarkComponent: false,
      morePopupList: '',
      componentId: '',
      selectNode: {
        label: '矢量数据'
      },
      selectLayerNode: null,
      selectLayerParams: null
    };
  },

  methods: {
    /**
     * 树节点
     * */
    // 初始化树节点
    createTreeData () {
      this.treeData.forEach(item => {
        item.icon = `${item.label}_s.png`;
        item.isCheck = true;
        item.children && item.children.length && item.children.forEach(option => {
          option.icon = `${option.label}.png`;
          option.isCheck = false;
          option.children = [];
          option.control = [];
          if (option.id === "1-3") {
            option.children.push({
              id: 'imageDefault',
              level: 3,
              label: '默认影像服务',
              control: [
                {
                  icon: "显示.png",
                  isCheck: false,
                  name: "显示"
                }
              ],
              attribute: {
                isEdit: false,
                isExist: true
              }
            })
          }
          const controlList = ['添加', '删除', '显示'];
          controlList.forEach(e => {
            option.control.push({
              name: e,
              isCheck: false,
              icon: `${e}.png`
            });
          });
        });
      });
    },

    // 树节点展开、收起、点击
    handleNode (data, state) {
      if (data.level == 3) return;
      if (data.children && data.children.length) {
        data.isCheck = state == 'expand' ? true : false;
        data.icon = data.isCheck ? `${data.label}_s.png` : `${data.label}.png`;

        if (data.level == 1) {
          const childrenNode = JSON.parse(JSON.stringify(data.children));
          this.$refs.leftTree.updateKeyChildren(data.id, childrenNode);
        } else {
          let parentNode = this.getParentNodeData(data.id);
          this.$refs.leftTree.updateKeyChildren(parentNode.id, parentNode.children);
        }


        if (data.level == 1) {
          if (state == 'collapse') {
            this.expandedList = [];
          } else if (state == 'expand') {
            this.expandedList = ['1', '1-1', '1-2', '1-3', '1-5'];
          }
        } else {
          let expandedList = this.expandedList;
          for (let i = 0; i < expandedList.length; i++) {
            const item = expandedList[i];
            if (state == 'collapse' && data.id == item) {
              expandedList.splice(i, 1);
              i++;
            } else if (state == 'expand' && expandedList.indexOf(data.id) == -1) {
              expandedList.push(data.id);
            }
          }
          this.expandedList = expandedList;
          console.log(expandedList);
        }
      }
    },

    // 树节点 hover
    hoverTreeNode (e, data) {
      e.stopPropagation();
      if (data.level == 3 || data.isCheck) return;
      data.icon = e.type == 'mouseover' ? `${data.label}_h.png` : `${data.label}.png`;
      if (data.level == 1) {
        const childrenNode = JSON.parse(JSON.stringify(data.children));
        this.$refs.leftTree.updateKeyChildren(data.id, childrenNode);
      } else {
        let treeData = this.getParentNodeData(data.id);
        this.$refs.leftTree.updateKeyChildren(treeData.id, treeData.children);
      }
    },

    // 节点控件 hover
    hoverNodeControl (e, data) {
      const controlIndex = e.target.getAttribute('data-index');
      if (!controlIndex) return;
      if (data.id == '1') {
        if (data.isCheck) return;
        data.icon = e.type == 'mouseover' ? `${data.label}_h.png` : `${data.label}.png`;
      } else {
        let controlNode = data.control[Number(controlIndex)];
        if (controlNode.isCheck) return;
        controlNode.icon = e.type == 'mouseover' ? `${controlNode.name}_h.png` : `${controlNode.name}.png`;
      }
      const childrenNode = (data.children && data.children.length) ? JSON.parse(JSON.stringify(data.children)) : [];
      this.$refs.leftTree.updateKeyChildren(data.id, childrenNode);
    },

    // 节点控件点击
    clickNodeControl (controlItem, data) {
      this.clearAddPopover();
      this.clearExpand();

      if (data.level == 2) {
        let curNode = this.getCurNodeData(data.id);
        if (controlItem.name != '添加' && (!curNode.children || !curNode.children.length)) return false;
      }

      data.control.forEach(item => {
        if (controlItem.name == item.name) {
          item.isCheck = !item.isCheck;
          if (item.name != '显示') {
            item.icon = item.isCheck ? `${controlItem.name}_s.png` : `${item.name}.png`;
          } else {
            item.icon = item.isCheck ? `隐藏_s.png` : `${item.name}.png`;
          }
        }

        if (item.name == '更多' && controlItem.name != '更多') {
          item.isCheck = false;
          item.icon = item.isCheck ? `${controlItem.name}_s.png` : `${item.name}.png`;
        }
      });

      switch (data.level) {
        case 2:
          this.clickNodeControlLevel2(controlItem, data);
          break;

        case 3:
          this.clickNodeControlLevel3(controlItem, data);
          break;

        default:
          break;
      }

      let parentNode = this.getParentNodeData(data.id);
      parentNode.children.map(e => { return e.id == data.id && (e.control = data.control); });
      this.$refs.leftTree.updateKeyChildren(parentNode.id, parentNode.children);
    },

    // 二级节点控件
    clickNodeControlLevel2 (controlItem, data) {
      this.closeMarkPanel(data.label);
      switch (controlItem.name) {
        case '添加':
          this.executeNodeControlLevel2(controlItem, data);
          break;

        case '删除':
          if (!data.children || !data.children.length) return;

          this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let parentNode = this.getParentNodeData(data.id);
            parentNode.children.forEach(item => {
              if (item.id == data.id) {
                item.children = [];
                item.icon = `${data.label}.png`;
                item.control.forEach(item => {
                  if (item.name == '显示') {
                    item.isCheck = false;
                    item.icon = '显示.png';
                  }

                  if (item.name == '删除') {
                    item.isCheck = false;
                    item.icon = '删除.png';
                  }
                });
              }
            });
            this.$refs.leftTree.updateKeyChildren(parentNode.id, parentNode.children);
            this.executeNodeControlLevel2(controlItem, data);
            this.message('删除成功!', 'success');
          }).catch(() => {
            this.message('已取消删除', 'info');
          });
          break;

        case '显示':
          let curNode = JSON.parse(JSON.stringify(data));
          if (!curNode.children || !curNode.children.length) return;
          curNode.children.forEach(item => {
            item.control.forEach(e => {
              if (e.name == '显示') {
                e.isCheck = controlItem.isCheck;
                e.icon = controlItem.isCheck ? '隐藏_s.png' : '显示.png';
              }
            });
            item.attribute.show = !controlItem.isCheck;
          });
          this.executeNodeControlLevel2(controlItem, data);
          this.$refs.leftTree.updateKeyChildren(curNode.id, curNode.children);
          break;

        default:
          break;
      }
    },

    // 二级节点方法
    executeNodeControlLevel2 (controlItem, data) {
      const { name, isCheck } = controlItem;
      const { id, label } = data;
      switch (label) {
        case '三维模型':
          switch (name) {
            case '添加':
              let addPopupEle = this.$refs[`addPopup${id}`];
              if (addPopupEle) {
                // this.addPopupList = ['三维模型文件', '三维场景服务', '三维服务'];
                this.addPopupList = ['三维模型文件', '三维服务'];
                addPopupEle.style.display = isCheck ? 'block' : 'none';
              }
              break;

            case '删除':
              this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.removeModel();
              break;

            case '显示':
              data.children.forEach(item => {
                const { resourceId } = item.attribute;
                item.attribute.show = !isCheck;
                this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.hideModel(resourceId, !isCheck);
              });
              break;

            default:
              break;
          }
          break;

        case '矢量数据':
        case '影像数据':
          switch (name) {
            case '添加':
              // this.addPopupList = ['在线服务', '本地服务'];
              this.addPopupList = ['在线服务'];
              let addPopupEle = this.$refs[`addPopup${id}`];
              if (addPopupEle) {
                addPopupEle.style.display = isCheck ? 'block' : 'none';
              }
              break;

            case '删除':
              this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.removeLayer();
              break;

            case '显示':
              data.children.forEach(item => {
                const { resourceId } = item.attribute;
                item.attribute.show = !isCheck;
                if (this.$refs.layerDialogEle) {
                  this.$refs.layerDialogEle._Layer.hideLayer(resourceId, !isCheck);
                  this.$refs.layerDialogEle._Layer.hideLayer(`${resourceId}_whiteFilm`, !isCheck);
                }
              });
              break;

            default:
              break;
          }
          break;

        case '标注信息':
          switch (name) {
            case '添加':
              this.showMarkComponent = isCheck;
              break;

            case '删除':
              this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.removeMark();
              break;

            case '显示':
              data.children.forEach(item => {
                item.attribute.show = !isCheck;
              });
              this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.hideMark('', !isCheck);
              break;

            default:
              break;
          }
          break;

        default:
          this.addPopupList = [];
          break;
      }
    },

    // 三级节点控件
    clickNodeControlLevel3 (controlItem, data) {
      const { name, isCheck } = controlItem;
      const { id } = data;
      switch (name) {
        case '更多':
          const { serverType } = data.attribute;
          let morePopupList = [];
          switch (serverType) {
            // case 'glb':
            // case 'gltf':
            // case '3DTileset':
            //   morePopupList = ['定位', '重命名'];
            //   break;

            case 'WMTS':
            case 'WMS':
            case 'XYZ':
              const { apiType, dataType } = data.attribute;
              if (apiType == 'rasterserver') {
                morePopupList = ['图层定位', '重命名'];
              } else if (apiType == 'mapserver') {
                switch (dataType) {
                  case 'label':
                    morePopupList = ['图层定位', '重命名', '属性查询'];
                    break;

                  default:
                    morePopupList = ['图层定位', '重命名', '样式设置', '属性查询'];
                    break;
                }
              }
              break;

            default:
              morePopupList = ['定位', '重命名'];
              break;
          }
          this.morePopupList = morePopupList;
          let morePopupEle = this.$refs[`morePopup${id}`];
          if (morePopupEle) {
            morePopupEle.style.display = isCheck ? 'block' : 'none';
          }
          break;

        case '删除':
          this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let parentNodeR = this.getParentNodeData(id);
            for (let i = 0; i < parentNodeR.children.length; i++) {
              const item = parentNodeR.children[i];
              if (item.id == id) {
                parentNodeR.children.splice(i, 1);
                i++;
              }
            }
            this.$refs.leftTree.updateKeyChildren(parentNodeR.id, parentNodeR.children);
            this.executeNodeControlLevel3(controlItem, data, parentNodeR);

            if (!parentNodeR.children.length) {
              let parentNodeR_P = this.getParentNodeData(parentNodeR.id);
              parentNodeR_P.children.forEach(item => {
                if (item.id == parentNodeR.id) {
                  item.isCheck = false;
                  item.icon = `${item.label}.png`;
                  item.control.forEach(e => {
                    if (e.name == '显示') {
                      e.isCheck = false;
                      e.icon = '显示.png';
                    }
                  });
                }
              });
              this.$refs.leftTree.updateKeyChildren(parentNodeR_P.id, parentNodeR_P.children);
            }
            this.message('删除成功!', 'success');
          }).catch((error) => {
            this.message('已取消删除', 'info');
          });

          setTimeout(() => {
            controlItem.isCheck = false;
            controlItem.icon = '删除.png';
          }, 100);
          break;

        case '显示':
          if (data.id === "imageDefault") {
            this.Global.defaultImageLayer.show = !isCheck;
          }
          let parentNodeH = this.getParentNodeData(id);
          let hideList = [];
          parentNodeH.children.forEach(item => {
            if (item.id == id) {
              item.control.forEach((option, index) => {
                if (option.name == name) {
                  item.control[index] = { ...controlItem };
                }
              });
              item.attribute.show = !isCheck;
              this.executeNodeControlLevel3(controlItem, data, parentNodeH);
            }

            item.control.forEach(option => {
              if (option.name == name && option.isCheck) {
                hideList.push(item);
              }
            });
          });

          let parentNodeH_P = this.getParentNodeData(parentNodeH.id);
          parentNodeH_P.children.forEach(item => {
            if (item.id == parentNodeH.id) {
              item.control.forEach(e => {
                if (e.name == '显示') {
                  const isAll = hideList.length == parentNodeH.children.length;
                  e.isCheck = isAll;
                  e.icon = isAll ? '隐藏_s.png' : '显示.png';
                }
              });
              item.children = parentNodeH.children;
            }
          });
          this.$refs.leftTree.updateKeyChildren(parentNodeH_P.id, parentNodeH_P.children);
          break;

        default:
          break;
      }
    },

    // 三级节点方法
    executeNodeControlLevel3 (controlItem, data, parentData) {
      const { name, isCheck } = controlItem;
      const { label } = parentData;
      const { resourceId } = data.attribute;

      switch (label) {
        case '三维模型':
          switch (name) {
            case '删除':
              this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.removeModel(resourceId);
              break;

            case '显示':
              this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.hideModel(resourceId, !isCheck);
              break;

            default:
              break;
          }
          break;

        case '矢量数据':
        case '影像数据':
          switch (name) {
            case '删除':
              this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.removeLayer(resourceId);
              this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.removeLayer(`${resourceId}_whiteFilm`);
              break;

            case '显示':
              this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.hideLayer(resourceId, !isCheck);
              this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.hideLayer(`${resourceId}_whiteFilm`, !isCheck);
              break;

            default:
              break;
          }
          break;

        case '标注信息':
          switch (name) {
            case '删除':
              this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.removeMark(resourceId);
              break;

            case '显示':
              this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.hideMark(resourceId, !isCheck);
              break;

            default:
              break;
          }
          break;

        default:
          break;
      }
    },

    // 三级节点重命名
    renameNode (data) {
      let parentNode = JSON.parse(JSON.stringify(this.$refs.leftTree.getNode(data.id).parent.data));
      let label = data.label.replace(/\s*/g, "");
      if (!label) {
        switch (parentNode.label) {
          case '三维模型':
            label = `我的模型_${parentNode.children.length}`;
            break;

          case '矢量数据':
            label = `我的矢量_${parentNode.children.length}`;
            break;

          case '影像数据':
            label = `我的影像_${parentNode.children.length}`;
            break;

          case '标注信息':
            label = `我的标注_${parentNode.children.length}`;
            break;

          default:
            break;
        }
      } else {
        parentNode.children.forEach(item => {
          if (item.id != data.id && item.label == label) {
            const labelList = parentNode.children.map(e => { return e.label; });
            label = this.unitListName(labelList, label);
          }
        });
      }
      data.label = label;
      data.attribute.isEdit = false;

      if (parentNode.label == '标注信息') {
        this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.renameMark(data.resourceId, label);
      }
    },

    // 点击 '添加' 弹窗
    clickAddPopupItem (data, name) {
      this.clearAddPopover();
      this.clearExpand();
      const { label } = data;
      this.selectNode = data;
      this.popupItemType = name;
      switch (label) {
        case '三维模型':
          this.showModelDialog = true;
          break;

        case '矢量数据':
        case '影像数据':
          name == '在线服务' && (this.showLayerDialog = true);
          break;

        case '标注信息':
          this.showMarkComponent = true;
          break;

        default:
          break;
      }
    },

    // 清除 '添加' 弹窗及状态
    clearAddPopover () {
      const parentNode = this.getCurNodeData('1');
      parentNode.children.forEach(item => {
        let addPopupEle = this.$refs[`addPopup${item.id}`];
        addPopupEle && (addPopupEle.style.display = 'none');
        item.control.map(e => { return e.name == '添加' && (e.icon = `${e.name}.png`) && (e.isCheck = false); });
      });
      this.$refs.leftTree.updateKeyChildren(parentNode.id, parentNode.children);
    },

    // 点击 '更多' 弹窗 
    clickMorePopupItem (curType, data) {
      const parentNode = this.getParentNodeData(data.id);
      const { label } = parentNode;
      const { resourceId } = data.attribute;
      switch (label) {
        case '三维模型':
          switch (curType) {
            case '定位':
              this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.locateModel(resourceId);
              break;

            case '重命名':
              data.attribute.isEdit = true;
              setTimeout(() => {
                this.$refs.renameInput && this.$refs.renameInput.focus();
              }, 100);
              break;

            default:
              break;
          }
          break;

        case '矢量数据':
        case '影像数据':
          switch (curType) {
            case '图层定位':
              const { position } = data.attribute;
              this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.setView(position);
              break;

            case '重命名':
              data.attribute.isEdit = true;
              setTimeout(() => {
                this.$refs.renameInput && this.$refs.renameInput.focus();
              }, 100);
              break;

            case '样式设置':
              this.selectLayerNode = data;
              this.componentId = 'layerStyle';
              break;

            case '属性查询':
              this.selectLayerNode = data;
              this.componentId = 'iQuery';
              break;

            default:
              break;
          }
          break;

        case '标注信息':
          switch (curType) {
            case '定位':
              this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.locateMark(resourceId);
              break;

            case '重命名':
              data.attribute.isEdit = true;
              setTimeout(() => {
                this.$refs.renameInput && this.$refs.renameInput.focus();
              }, 100);
              break;

            default:
              break;
          }
          break;
        default:
          break;
      }
      this.clearExpand(false);
    },

    // 清除 '更多' 弹窗及状态
    clearExpand () {
      const parentNode = this.getCurNodeData('1');
      parentNode.children.forEach(item => {
        if (item.children && item.children.length) {
          item.children.forEach(option => {
            let expandEle = this.$refs[`morePopup${option.id}`];
            expandEle && (expandEle.style.display = 'none');
            option.control.map(e => { return e.name == '更多' && (e.icon = `${e.name}.png`) && (e.isCheck = false); });
            option.isEdit = false;
          });
          this.$refs.leftTree.updateKeyChildren(item.id, item.children);
        }
      });
      this.$refs.leftTree.updateKeyChildren(parentNode.id, parentNode.children);
    },

    /**
     * 三维模型
     * */
    // 追加模型节点
    appendModelNode (option) {
      const parentNode = this.getCurNodeData('1-1');
      if (parentNode.children.length > window.resourceAstrict.modelAstrict) return this.message(`三维模型最多允许加载${window.resourceAstrict.modelAstrict}个`);

      const { serverName } = option;
      let node = {
        id: `1-1-${parentNode.children.length + 1}`,
        level: 3,
        label: serverName,
        control: [],
        attribute: option
      };
      this.appendNode({ node, parentNode });
    },

    closeModelDialog () {
      this.showModelDialog = false;
    },

    /**
     * 矢量数据
     * 影像数据
     * */
    appendLayerNode (option) {
      const { id, label } = this.selectNode;
      const parentNode = this.getCurNodeData(id);
      if (parentNode.children.length > window.resourceAstrict.layerAstrict) return this.message(`${label}最多允许加载${window.resourceAstrict.layerAstrict}个`);

      const { serverName } = option;
      let node = {
        id: `${id}-${parentNode.children.length + 1}`,
        level: 3,
        label: serverName,
        control: [],
        attribute: option
      };
      this.appendNode({ node, parentNode });
    },

    closeLayerDialog () {
      this.showLayerDialog = false;
    },

    // 矢量样式设置
    setLayerStyle (option) {
      let { id, attribute } = option;
      let parentNode = this.getParentNodeData(id);
      parentNode.children.forEach(item => {
        if (item.id == id) {
          attribute.isFirst = false;
          item.attribute = attribute;
        }
      });
      this.$refs.leftTree.updateKeyChildren(parentNode.id, parentNode.children);
      this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.loadLayer(attribute);
    },

    // 清除矢量 '更多' 组件
    closeLayerNodeLevel3 () {
      this.componentId = '';
      this.selectLayerNode = null;
    },

    /**
     * 标注信息
     * */
    appendMarkNode (option) {
      const parentNode = this.getCurNodeData('1-5');
      if (parentNode.children.length > window.resourceAstrict.markAstrict) return this.message(`标注信息最多允许加载${window.resourceAstrict.markAstrict}个`);

      const { name } = option;
      let node = {
        id: `1-5-${parentNode.children.length + 1}`,
        level: 3,
        label: name,
        attribute: option,
        control: []
      };
      this.appendNode({
        node, parentNode
      });
    },

    closeMarkPanel (label) {
      if (label != '标注信息' && this.$refs.leftTree) {
        this.showMarkComponent = false;
        let treeNode = JSON.parse(JSON.stringify(this.$refs.leftTree.getNode('1').data));
        treeNode.children.forEach(item => {
          if (item.label == '标注信息') {
            item.control.forEach((option, index) => {
              if (option.name == '添加') {
                item.control[index] = {
                  icon: `${option.name}.png`,
                  isCheck: false,
                  name: "添加"
                };
              }
            });
          }
        });
        this.$refs.leftTree.updateKeyChildren(treeNode.id, treeNode.children);
      }
    },

    // 新增三级节点
    appendNode (option) {
      const { node, parentNode, callback } = option;
      const { serverType, isExist } = node.attribute;
      let controlList = [];
      if (isExist) {
        controlList = ['更多', '删除', '显示'];
      } else {
        controlList = ['删除'];
      }
      controlList.forEach(item => {
        if (item == '显示') {
          const hideControl = parentNode.control.find(e => e.name == '显示');
          node.control.push({
            name: item,
            isCheck: hideControl.isCheck,
            icon: hideControl.isCheck ? '隐藏_s.png' : `${item}.png`,
          });
        } else {
          node.control.push({
            name: item,
            isCheck: false,
            icon: `${item}.png`,
          });
        }
      });

      // 更新子节点
      let childrenNode = JSON.parse(JSON.stringify(parentNode.children));
      childrenNode.push(node);
      this.$refs.leftTree.updateKeyChildren(parentNode.id, childrenNode);
      // 更新父节点
      let parentNodeSuperior = this.getCurNodeData('1');
      parentNodeSuperior.children.forEach(item => {
        if (item.id == parentNode.id) {
          item.control.map(e => { return e.name == '添加' && (e.icon = `${e.name}.png`) && (e.isCheck = false); });
          item.icon = `${item.label}_s.png`;
          item.isCheck = true;
        }
      });
      this.$refs.leftTree.updateKeyChildren(parentNodeSuperior.id, parentNodeSuperior.children);

      this.$nextTick(() => {
        console.log(this.treeData)
        typeof callback == 'function' && callback();
      });
    },

    // 获取父节点数据
    getParentNodeData (id) {
      let curNode = this.$refs.leftTree.getNode(id);
      let parentNode = curNode ? JSON.parse(JSON.stringify(curNode.parent.data)) : null;
      return parentNode;
    },

    // 获取当前节点数据
    getCurNodeData (id) {
      let curNode = this.$refs.leftTree.getNode(id);
      let nodeData = curNode ? JSON.parse(JSON.stringify(curNode.data)) : null;
      return nodeData;
    },

    // 检查是否有重名
    unitListName (list, n) {
      function check (name) {
        let n = name.match(/[^\.]*/)[0];
        return function (a) {
          return a.indexOf(n) == 0;
        };
      }
      list = list.filter(check(n));
      let on = n.match(/([^\.]*)(.*)/);

      // 重名文件最多10000个
      for (let i = 1; i < 10000; i++) {
        let nn = on[1] + '_' + String(i);
        if (!list.find((element) => (element == nn + on[2])))
          return nn + on[2];
      }
    },

    // 判断树节点是否为空
    isFirstUpdataNode () {
      let childrenNode = [];
      this.treeData[0].children.forEach(item => {
        if (item.children && item.children.length) {
          childrenNode.push(...item.children);
        }
      });
      return childrenNode.length ? false : true;
    },

    // 判断资源是否存在
    async fileExist (url) {
      let isExist = null;
      try {
        let res = await this.$get(url);
        isExist = true;
      } catch (error) {
        isExist = false;
      }
      return isExist;
    },

    // 提示
    message (message = '警告', type = 'warning') {
      this.$message({
        message: message,
        type: type
      });
    },

    /**
     * 打开配置文件
     * */
    loadFile (fileData) {
      if (this.viewer.scene.primitives._primitives.length) {
        this.viewer.scene.primitives._primitives.forEach(item => {
          if (item.attribute) this.viewer.scene.primitives.remove(item);
        });
      }

      if (this.viewer.imageryLayers._layers.length) {
        this.viewer.imageryLayers._layers.forEach(item => {
          if (item.attribute) this.viewer.imageryLayers.remove(item);
        });
      }

      if (this.viewer.dataSources._dataSources.length) {
        this.viewer.dataSources._dataSources.forEach(item => {
          item.entities.removeAll();
        });
      }

      this.$nextTick(() => {
        this.treeData = fileData;
        fileData[0].children.forEach(item => {
          if (item.children && item.children.length) {
            const childrenData = item.children;
            switch (item.label) {
              case '三维模型':
                this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.loadModelFile(childrenData);
                break;

              case '矢量数据':
              case '影像数据':
                this.$refs.layerDialogEle && this.$refs.layerDialogEle._Layer.loadLayerFile(childrenData);
                break;

              case '标注信息':
                this.$refs.markInfoEle && this.$refs.markInfoEle._Mark.loadMarkFile(childrenData);
                break;

              default:
                break;
            }
          }
        });
      });
    },

    getTreeData () {
      const treeData = this.getCurNodeData('1');
      this.Global.treeData = this.treeData;
    },

    addListen () {
      this.eventBus.$on('getTreeData', this.getTreeData);
      this.eventBus.$on('loadFile', this.loadFile);
    },

    removeListen () {
      this.eventBus.$on('getTreeData', this.getTreeData);
      this.eventBus.$off('loadFile', this.loadFile);
    },

    handleDocumentClick (e) {
      const curKey = this.$refs.leftTree && this.$refs.leftTree.getCurrentKey();
      if (!curKey) {
        this.clearAddPopover();
        this.clearExpand();
      }
    }
  },

  created () {
    this.addListen();
  },

  mounted () {
    this.viewer = this.Global.viewer;
    this.isLoad = true;
    this.createTreeData();
    document.addEventListener('click', this.handleDocumentClick);
  },

  beforeDestroy () {
    // this.removeListen();
    this.createTreeData();
    this.isLoad = false;
    document.removeEventListener('click', this.handleDocumentClick);
  }
}
</script>

<style lang="less" scoped>
.left-sub {
  position: relative;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  background-color: #444444;
  z-index: 11;

  /deep/.el-tree {
    padding: 16px 0 0 8px;
    box-sizing: border-box;
    background-color: #444444;

    .el-tree-node>.el-tree-node__content {
      padding-left: 8px !important;
    }

    .el-tree-node__children>.el-tree-node>.el-tree-node__content {
      padding-left: 24px !important;
    }

    .el-tree-node__children .el-tree-node .el-tree-node__children .el-tree-node .el-tree-node__content {
      padding-left: 62px !important;
    }

    .el-tree-node__children {
      overflow: unset !important;
    }

    .el-tree-node__content {
      height: 32px;
      box-sizing: border-box;

      &:hover {
        background-color: rgba(74, 88, 120, 0.4);
        border-radius: 16px 0px 0px 16px;
        color: #7bbaff;
      }

      .el-tree-node__expand-icon {
        padding: 8px;
      }

      .tree-slot {
        width: 100%;
        height: 100%;

        .level-1,
        .level-2,
        .level-3 {
          position: relative;
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 100%;
          font-size: 14px;
          color: #ffffff;

          .left-box,
          .right-box {
            display: flex;
            align-items: center;
            height: 100%;
          }

          .left-box {
            img {
              width: 12px;
              height: 12px;
              margin-right: 8px;
            }

            .el-input__inner {
              width: 100px;
              height: 25px;
              padding: 0 5px;
              box-sizing: border-box;
              background-color: rgba(0, 0, 0, 0);
              font-size: 14px;
              color: #ffffff;
            }

            .box-label {
              display: flex;
              align-items: center;
              width: 100px;

              span {
                display: inline-block;
              }

              img {
                width: 16px;
                height: 16px;
                margin-left: 5px;
              }
            }
          }

          .right-box {
            padding-right: 24px;
            box-sizing: border-box;

            .img-box {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 20px;
              height: 20px;
              margin-left: 4px;

              img {
                width: 12px;
                height: 12px;
              }
            }
          }

          .not-exist {
            padding-right: 48px;
          }

          .popup-box {
            display: none;
            position: absolute;
            right: 1px;
            top: 34px;
            width: 112px;
            background: rgba(0, 0, 0, 0.4);
            box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2);
            border-radius: 8px;
            border: 1px solid #444444;
            backdrop-filter: blur(2px);
            padding: 6px 4px;
            box-sizing: border-box;
            pointer-events: all;
            z-index: 9999;

            .item {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 100%;
              height: 32px;
              border-radius: 4px;
              font-size: 14px;
              font-family: AlibabaPuHuiTiR;
              color: #ffffff;

              &:hover {
                background-color: rgba(74, 88, 120, 0.4);
              }
            }
          }
        }
      }
    }
  }

  /deep/.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content,
  /deep/.el-tree-node:focus>.el-tree-node__content {
    background-color: rgba(74, 88, 120, 0.4) !important;
    border-radius: 16px 0px 0px 16px !important;
    color: #1e88ff !important;
  }

  .mask-box {
    position: fixed;
    top: 94px;
    left: 0;
    width: 100%;
    height: calc(100% - 94px);
    background-color: #fff;
    z-index: 999;
  }
}
</style>